<template>
	<view class="container">
		<view class="box-bg">
			<uni-nav-bar class="nav" shadow left-icon="left" leftText="返回" rightText="重新扫描" @clickRight="rescan"
				@clickLeft="clickLeft" />
		</view>
		<scroll-view scroll-y class="box">
			<view class="item" v-for="(item, index) in blueDeviceList" :key="index" @click="connect(item, index)"
				:class="{ active: blueIndex === index }">
				<view>
					<text>{{ item.name }}</text>
				</view>
				<view>
					<text>{{ item.deviceId }}</text>
				</view>
			</view>
		</scroll-view>
	</view>
</template>

<script>
	import CTPL from "../../web-CTPL-SDK/ctpl.js";
	import {
		ref
	} from "vue";
	export default {
		data() {
			return {
				blueDeviceList: [], //蓝牙设备列表
				blueName: "", //蓝牙设备名称
				blueDeviceId: "", //蓝牙设备特征值
				blueIndex: -1,
			};
		},
		async onLoad() {
			console.log("开始")
			await CTPL.init();
			console.log("初始化结束")
			this.discoveryList();
		},
		methods: {
			clickLeft() {
				uni.navigateBack();
			},
			async discoveryList() {
				uni.showLoading();
				console.log("开始扫描")
				const res = await CTPL.discovery();
				console.log("扫描结束")
				this.blueDeviceList = res;
				uni.hideLoading();
			},
			//重新扫描
			rescan() {
				this.blueDeviceList = [];
				this.discoveryList();
			},
			//开始连接蓝牙
			connect(data, index) {
				CTPL.connect(data.deviceId);
				this.blueName = data.name;
				this.blueDeviceId = data.deviceId;
				this.blueIndex = index;
				setTimeout(() => {
					uni.navigateTo({
						url: `index?blename=${this.blueName}&deviceId=${this.blueDeviceId}`,
					});
				}, 100);
			},
		},
	};
</script>

<style lang="scss">
	.container {
		height: 100vh;
	}

	$nav-height: 30px;

	.box-bg {
		background-color: #f5f5f5;

		.nav {
			text {
				font-size: 28rpx !important;
			}

			.uni-nav-bar-right-text {
				color: #1aad19 !important;
			}
		}
	}

	.city {
		/* #ifndef APP-PLUS-NVUE */
		display: flex;
		/* #endif */
		flex-direction: row;
		align-items: center;
		justify-content: flex-start;
		// width: 160rpx;
		margin-left: 4px;
	}

	.input-view {
		/* #ifndef APP-PLUS-NVUE */
		display: flex;
		/* #endif */
		flex-direction: row;
		// width: 500rpx;
		flex: 1;
		background-color: #f8f8f8;
		height: $nav-height;
		border-radius: 15px;
		padding: 0 15px;
		flex-wrap: nowrap;
		margin: 7px 0;
		line-height: $nav-height;
	}

	.input-uni-icon {
		line-height: $nav-height;
	}

	.nav-bar-input {
		height: $nav-height;
		line-height: $nav-height;
		/* #ifdef APP-PLUS-NVUE */
		width: 370rpx;
		/* #endif */
		padding: 0 5px;
		font-size: 14px;
		background-color: #f8f8f8;
	}

	.box {
		height: calc(100vh - 30px);
	}

	.item {
		display: flex;
		flex-direction: column;
		justify-content: center;
		height: 110rpx;
		padding-left: 20px;
		border-bottom: 1px solid #e5e5e5;
	}

	.active {
		background-color: #e5e5e5;
	}
</style>